<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="applicationRegister"
    @ok="confirmSubmit"
    @close="drawerReset"
    width="424"
    showFooter
    isAbsolute
    getContainer=".page-wrapper"
  >
    <div class="application-drawer" ref="eleRef">
      <BasicForm @register="applicationForm" />
    </div>
  </BasicDrawer>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { BasicDrawer, useDrawerInner } from '@/components/Drawer'
import { BasicForm, FormSchema, useForm } from '@/components/Form/index'
import { operateActionType } from '@/types/enum'
import { numTransString, scrollToFirstError } from '@/utils'
import { getApplicationFormConfig } from '../dataSource'
import { message } from 'ant-design-vue'
import { ApplicationRecord } from '@/types/deployUpgrade'
import { cloneDeep } from 'lodash-es'
import api from '@/api'

const { addApp, editApp } = api

const emit = defineEmits(['operateSuccess', 'register'])
const eleRef = ref<null | HTMLElement>(null)

const drawerInfo = reactive<{ type: string; record: Partial<ApplicationRecord> }>({
  type: '',
  record: {}
})

const applicationFormConfig = getApplicationFormConfig()
const [applicationForm, { setFieldsValue, getFieldsValue, validate, resetFields, updateSchema }] =
  useForm(applicationFormConfig)

const [applicationRegister, { closeDrawer, changeOkLoading }] = useDrawerInner(async (data) => {
  drawerInfo.type = data.type
  if (data.type === operateActionType.EDIT) {
    let record = cloneDeep(data.record)
    drawerInfo.record = record
    setFieldsValue({
      ...record,
      appPlatform: numTransString(record.appPlatform),
      appStatus: numTransString(record.appStatus)
    })
  }
})

const drawerReset = () => {
  changeOkLoading(false)
  resetFields()
}

// 提交数据
const confirmSubmit = async () => {
  try {
    await validate()
    let formValue = getFieldsValue()
    changeOkLoading(true)
    if (drawerInfo.type === operateActionType.ADD) {
      await addApp({
        ...formValue
      })
    } else if (drawerInfo.type === operateActionType.EDIT) {
      await editApp({
        ...formValue,
        id: drawerInfo.record.id
      })
    }
    message.success(drawerInfo.type === operateActionType.ADD ? '应用新增成功' : '应用编辑成功')
    closeDrawer()
    drawerReset()
    emit('operateSuccess')
  } catch (error) {
    changeOkLoading(false)
    scrollToFirstError(eleRef.value)
  }
}
</script>

<style lang="less" scoped>
.application-drawer {
  padding: 8px 16px;
  :deep(.ant-form-item-label) {
    font-weight: 600;
  }
}
</style>
